/**
 * 骗子酒馆
 * @author: mitu2
 * @author ManUpMan
 * @param options
 */
export function init(options = {}) {
  const { currentUser } = window.Label || {
    currentUser:
      window.location.hostname + "_Player_" + Math.floor(Math.random() * 10000),
  };
  const baseLT = {
    player: currentUser,
    baseUrl: "https://game.metoo.ink",
    globalName: "LT",
    op: {},
  };
  const LT = Object.assign({}, baseLT, options);
  const LOG = (msg, level = "#42c02e") => {
    console.log(
      `%c[LiarTavern]%c${msg}`,
      "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #606060; font-weight: bold;",
      `padding: 2px 1px; border-radius: 0 3px 3px 0; color: #fff; background: ${level};`
    );
  };
  const LOG_ERR = (msg) => LOG(msg, "#fb415e");
  const doApi = (path, params) => {
    params = params ? `&${params}` : "";
    return fetch(`${LT.baseUrl}/${path}?player=${LT.player}${params}`).then(
      (resp) =>
        new Promise((resolve, reject) => {
          if (resp.status !== 200) reject(resp);
          resolve(resp);
        }).catch((err) => {
          err.json().then((json) => {
            LOG_ERR(json.message);
          });
          throw err;
        })
    );
  };
  const APIS = {
    play: (uuid) =>
      uuid
        ? doApi(`api/liar-tavern-game/${uuid}/play`)
        : doApi(`api/liar-tavern-game/play`),
    watch: (uuid, version) =>
      doApi(`api/liar-tavern-game/${uuid}/watch`, `version=${version}`),
    cards: (uuid, useCards) =>
      doApi(`api/liar-tavern-game/${uuid}/cards`, `use=${useCards}`),
    bang: (uuid) => doApi(`api/liar-tavern-game/${uuid}/bang`),
  };
  const PRIVATE = {
    watchInterval: -1,
    waitPlayer: "",
    NONE: () => {},
    selectedCards: [],
  };

  // 创建可视化UI
  function createUI() {
    // 移除旧UI如果存在
    const oldUI = document.getElementById("liar-tavern-ui");
    if (oldUI) oldUI.remove();

    // 创建主容器
    const uiContainer = document.createElement("div");
    uiContainer.id = "liar-tavern-ui";
    uiContainer.style.position = "fixed";
    uiContainer.style.bottom = "20px";
    uiContainer.style.right = "20px";
    uiContainer.style.width = "350px";
    uiContainer.style.backgroundColor = "#2c3e50";
    uiContainer.style.border = "none";
    uiContainer.style.borderRadius = "12px";
    uiContainer.style.padding = "20px";
    uiContainer.style.zIndex = "9999";
    uiContainer.style.boxShadow = "0 8px 30px rgba(0,0,0,0.3)";
    uiContainer.style.color = "#ecf0f1";
    uiContainer.style.transition = "all 0.3s ease";
    uiContainer.style.overflow = "hidden";

    // 添加悬停效果
    uiContainer.addEventListener("mouseenter", () => {
      uiContainer.style.boxShadow = "0 12px 40px rgba(0,0,0,0.4)";
      uiContainer.style.transform = "translateY(-5px)";
    });
    uiContainer.addEventListener("mouseleave", () => {
      uiContainer.style.boxShadow = "0 8px 30px rgba(0,0,0,0.3)";
      uiContainer.style.transform = "translateY(0)";
    });

    // 标题区域
    const titleContainer = document.createElement("div");
    titleContainer.style.display = "flex";
    titleContainer.style.alignItems = "center";
    titleContainer.style.marginBottom = "15px";
    titleContainer.style.paddingBottom = "10px";
    titleContainer.style.borderBottom = "2px solid #34495e";

    // 图标
    const icon = document.createElement("div");
    icon.innerHTML = "🎴";
    icon.style.fontSize = "24px";
    icon.style.marginRight = "10px";
    titleContainer.appendChild(icon);

    // 标题
    const title = document.createElement("h3");
    title.textContent = "骗子酒馆";
    title.style.margin = "0";
    title.style.color = "#ecf0f1";
    title.style.fontWeight = "600";
    title.style.fontSize = "20px";
    title.style.letterSpacing = "0.5px";
    titleContainer.appendChild(title);

    uiContainer.appendChild(titleContainer);

    // 玩家信息
    const playerInfo = document.createElement("div");
    playerInfo.id = "lt-player-info";
    playerInfo.style.marginBottom = "15px";
    playerInfo.style.padding = "8px 12px";
    playerInfo.style.backgroundColor = "#34495e";
    playerInfo.style.borderRadius = "6px";
    playerInfo.style.fontSize = "14px";
    playerInfo.style.display = "flex";
    playerInfo.style.alignItems = "center";

    const playerIcon = document.createElement("span");
    playerIcon.textContent = "👤";
    playerIcon.style.marginRight = "8px";
    playerInfo.appendChild(playerIcon);

    const playerText = document.createElement("span");
    playerText.textContent = `玩家: ${LT.player}`;
    playerInfo.appendChild(playerText);

    uiContainer.appendChild(playerInfo);

    // 我的牌区域
    const myCardsSection = document.createElement("div");
    myCardsSection.style.marginBottom = "20px";

    const myCardsTitle = document.createElement("h4");
    myCardsTitle.textContent = "我的手牌";
    myCardsTitle.style.margin = "0 0 10px 0";
    myCardsTitle.style.color = "#bdc3c7";
    myCardsTitle.style.fontSize = "16px";
    myCardsTitle.style.fontWeight = "500";
    myCardsTitle.style.display = "flex";
    myCardsTitle.style.alignItems = "center";

    const cardsIcon = document.createElement("span");
    cardsIcon.textContent = "🃏";
    cardsIcon.style.marginRight = "8px";
    myCardsTitle.appendChild(cardsIcon);
    myCardsTitle.appendChild(document.createTextNode(""));

    myCardsSection.appendChild(myCardsTitle);

    const myCardsContainer = document.createElement("div");
    myCardsContainer.id = "lt-my-cards";
    myCardsContainer.style.display = "flex";
    myCardsContainer.style.flexWrap = "wrap";
    myCardsContainer.style.gap = "8px";
    myCardsContainer.style.marginBottom = "5px";
    myCardsSection.appendChild(myCardsContainer);

    uiContainer.appendChild(myCardsSection);

    // 选中的牌区域
    const selectedSection = document.createElement("div");
    selectedSection.style.marginBottom = "20px";

    const selectedTitle = document.createElement("h4");
    selectedTitle.textContent = "已选牌 (最多3张)";
    selectedTitle.style.margin = "0 0 10px 0";
    selectedTitle.style.color = "#bdc3c7";
    selectedTitle.style.fontSize = "16px";
    selectedTitle.style.fontWeight = "500";
    selectedTitle.style.display = "flex";
    selectedTitle.style.alignItems = "center";

    selectedSection.appendChild(selectedTitle);

    const selectedCardsContainer = document.createElement("div");
    selectedCardsContainer.id = "lt-selected-cards";
    selectedCardsContainer.style.display = "flex";
    selectedCardsContainer.style.flexWrap = "wrap";
    selectedCardsContainer.style.gap = "8px";
    selectedCardsContainer.style.minHeight = "50px";
    selectedCardsContainer.style.backgroundColor = "rgba(46, 204, 113, 0.1)";
    selectedCardsContainer.style.padding = "12px";
    selectedCardsContainer.style.borderRadius = "8px";
    selectedCardsContainer.style.border = "1px dashed rgba(46, 204, 113, 0.3)";
    selectedCardsContainer.style.transition = "all 0.3s ease";
    selectedSection.appendChild(selectedCardsContainer);

    uiContainer.appendChild(selectedSection);

    // 操作按钮区域
    const buttonContainer = document.createElement("div");
    buttonContainer.style.display = "flex";
    buttonContainer.style.gap = "10px";
    buttonContainer.style.marginBottom = "20px";

    // 按钮样式函数
    const createButton = (text, color, hoverColor) => {
      const btn = document.createElement("button");
      btn.textContent = text;
      btn.style.padding = "6px 4px";
      btn.style.backgroundColor = color;
      btn.style.color = "white";
      btn.style.border = "none";
      btn.style.borderRadius = "6px";
      btn.style.fontSize = "10px";
      btn.style.cursor = "pointer";
      btn.style.fontWeight = "500";
      btn.style.flex = "1";
      btn.style.transition = "all 0.2s ease";

      btn.addEventListener("mouseenter", () => {
        btn.style.backgroundColor = hoverColor;
        btn.style.transform = "translateY(-2px)";
      });

      btn.addEventListener("mouseleave", () => {
        btn.style.backgroundColor = color;
        btn.style.transform = "translateY(0)";
      });

      return btn;
    };

    // 发送按钮
    const sendButton = createButton("出牌", "#2ecc71", "#27ae60");
    sendButton.id = "lt-send-button";
    sendButton.onclick = () => {
      if (PRIVATE.selectedCards.length === 0) {
        alert("请先选择要出的牌");
        return;
      }
      LT.cards(...PRIVATE.selectedCards);
      PRIVATE.selectedCards = [];
      updateSelectedCardsUI();
    };
    buttonContainer.appendChild(sendButton);

    // 质疑按钮
    const bangButton = createButton("质疑", "#e74c3c", "#c0392b");
    bangButton.onclick = () => {
      LT.bang();
    };
    buttonContainer.appendChild(bangButton);

    // 刷新按钮
    const refreshButton = createButton("刷新", "#3498db", "#2980b9");
    refreshButton.onclick = () => {
      LT.show();
    };
    buttonContainer.appendChild(refreshButton);

    uiContainer.appendChild(buttonContainer);

    // 状态信息
    const statusInfo = document.createElement("div");
    statusInfo.id = "lt-status-info";
    statusInfo.style.marginTop = "10px";
    statusInfo.style.padding = "12px";
    statusInfo.style.backgroundColor = "rgba(236, 240, 241, 0.1)";
    statusInfo.style.color = "white";
    statusInfo.style.borderRadius = "8px";
    statusInfo.style.fontSize = "14px";
    statusInfo.style.lineHeight = "1.5";
    statusInfo.style.minHeight = "60px";
    statusInfo.style.borderLeft = "4px solid #3498db";
    uiContainer.appendChild(statusInfo);

    document.body.appendChild(uiContainer);
  }

  // 更新我的牌UI
  function updateMyCardsUI() {
    const myCardsContainer = document.getElementById("lt-my-cards");
    if (!myCardsContainer) return;

    myCardsContainer.innerHTML = "";

    const myPlayerData = PRIVATE.playerDataList?.find(
      (it) => it.name === LT.player
    );
    if (!myPlayerData) return;

    // 统计每种牌的数量
    const cardCounts = {};
    myPlayerData.items.forEach((card) => {
      cardCounts[card] = (cardCounts[card] || 0) + 1;
    });

    // 创建牌按钮
    Object.entries(cardCounts).forEach(([card, count]) => {
      const isRed = true;
      const cardButton = document.createElement("button");
      //   cardButton.textContent = `${card} (${count})`;
      cardButton.style.width = "40px";
      cardButton.style.height = "60px";
      cardButton.style.padding = "0";
      cardButton.style.backgroundColor = "white";
      cardButton.style.border = "1px solid #d0d0d0";
      cardButton.style.borderRadius = "6px";
      cardButton.style.cursor = "pointer";
      cardButton.style.margin = "4px";
      cardButton.style.boxShadow = "1px 1px 3px rgba(0,0,0,0.3)";
      cardButton.style.display = "flex";
      cardButton.style.flexDirection = "column";
      cardButton.style.justifyContent = "space-between";
      cardButton.style.alignItems = "center";
      cardButton.style.fontWeight = "bold";
      cardButton.style.fontSize = "20px";
      cardButton.style.position = "relative";
      cardButton.style.transition = "all 0.2s ease";

      // 左上角数值
      const topValue = document.createElement("div");
      topValue.textContent = card;
      topValue.style.position = "absolute";
      topValue.style.top = "2px";
      topValue.style.left = "2px";
      topValue.style.fontSize = "10px";
      topValue.style.color = isRed ? "red" : "black";
      cardButton.appendChild(topValue);

      // 右下角数值 (倒置)
      const bottomValue = document.createElement("div");
      bottomValue.textContent = card;
      bottomValue.style.position = "absolute";
      bottomValue.style.bottom = "2px";
      bottomValue.style.right = "2px";
      bottomValue.style.transform = "rotate(180deg)";
      bottomValue.style.fontSize = "10px";
      bottomValue.style.color = isRed ? "red" : "black";
      cardButton.appendChild(bottomValue);

      // 中间花色
      const centerSuit = document.createElement("div");
      centerSuit.textContent = "🤡";
      centerSuit.style.margin = "auto";
      centerSuit.style.fontSize = "15px";
      centerSuit.style.color = isRed ? "red" : "black";
      cardButton.appendChild(centerSuit);

      // 卡牌数量显示 (放在右上角)
      const countBadge = document.createElement("div");
      countBadge.textContent = count;
      countBadge.style.position = "absolute";
      countBadge.style.top = "2px";
      countBadge.style.right = "0px";
      countBadge.style.backgroundColor = "rgba(0,0,0,0.7)";
      countBadge.style.color = "white";
      countBadge.style.borderRadius = "50%";
      countBadge.style.width = "16px";
      countBadge.style.height = "16px";
      countBadge.style.display = "flex";
      countBadge.style.justifyContent = "center";
      countBadge.style.alignItems = "center";
      countBadge.style.fontSize = "10px";
      cardButton.appendChild(countBadge);

      cardButton.onclick = () => {
        if (PRIVATE.selectedCards.length >= 3) {
          alert("最多只能选择3张牌");
          return;
        }

        // 检查是否已经有这个类型的牌被选中
        const existingCardIndex = PRIVATE.selectedCards.findIndex(
          (c) => c.key === card
        );

        if (existingCardIndex >= 0) {
          // 增加已选牌的数量
          PRIVATE.selectedCards[existingCardIndex].size += 1;
        } else {
          // 添加新牌
          PRIVATE.selectedCards.push({
            key: card,
            size: 1,
          });
        }

        updateSelectedCardsUI();
      };

      myCardsContainer.appendChild(cardButton);
    });
  }

  // 更新已选牌UI
  function updateSelectedCardsUI() {
    const selectedCardsContainer = document.getElementById("lt-selected-cards");
    if (!selectedCardsContainer) return;

    selectedCardsContainer.innerHTML = "";

    PRIVATE.selectedCards.forEach((card, index) => {
      const cardBadge = document.createElement("div");
      cardBadge.textContent = `${card.key}_${card.size}`;
      cardBadge.style.padding = "3px 6px";
      cardBadge.style.backgroundColor = "rgb(44, 62, 80,0.8)";
      cardBadge.style.color = "white";
      cardBadge.style.borderRadius = "10px";
      cardBadge.style.display = "inline-flex";
      cardBadge.style.alignItems = "center";
      cardBadge.style.marginRight = "5px";
      cardBadge.style.fontSize = "12px";

      // 添加删除按钮
      const removeButton = document.createElement("span");

      removeButton.textContent = "❌";
      removeButton.style.marginLeft = "5px";
      removeButton.style.cursor = "pointer";
      removeButton.onclick = (e) => {
        e.stopPropagation();
        if (card.size > 1) {
          card.size -= 1;
        } else {
          PRIVATE.selectedCards.splice(index, 1);
        }
        updateSelectedCardsUI();
      };

      cardBadge.appendChild(removeButton);
      selectedCardsContainer.appendChild(cardBadge);
    });
  }

  // 更新状态信息
  function updateStatusInfo(message, isError = false) {
    const statusInfo = document.getElementById("lt-status-info");
    if (!statusInfo) return;

    statusInfo.textContent = message;
    statusInfo.style.color = isError ? "#f44336" : "#333";
  }

  LT.play = async function (roomId) {
    const playResp = await APIS.play(roomId);
    console.clear();
    const { creator, uuid } = await playResp.json();
    let ots = "";
    if (LT.baseUrl !== baseLT.baseUrl) {
      ots = `, baseUrl: '${LT.baseUrl}'`;
    }
    if (creator === LT.player) {
      LOG(
        `已创建一个酒馆, 需满足4人开始游戏, 邀请方式对方控制台输入> import('${LT.baseUrl}/liar-tavern-game-ui.js').then(({init}) => init({uuid: '${uuid}'${ots}}))`
      );
      updateStatusInfo(`您创建了酒馆，等待其他玩家加入...`);
    } else {
      LOG(
        `已加入${creator}的酒馆, 需满足4人开始游戏, 邀请方式对方控制台输入> import('${LT.baseUrl}/liar-tavern-game-ui.js').then(({init}) => init({uuid: '${uuid}'${ots}}))`
      );
      updateStatusInfo(`您加入了 ${creator} 的酒馆`);
    }
    if (PRIVATE.watchInterval || PRIVATE.watchInterval > 0) {
      clearInterval(PRIVATE.watchInterval);
    }
    PRIVATE.uuid = uuid;
    let version = 0;
    PRIVATE.watchInterval = setInterval(async () => {
      const watchResp = await APIS.watch(PRIVATE.uuid, version);
      const { events, lastVersion, playerDataList } = await watchResp.json();
      PRIVATE.playerDataList = playerDataList;
      const refreshItems = (record) => {
        let op = {};
        let _record = record || [];
        for (let recordElement of _record) {
          let size = 1;
          while (op[`${recordElement}_${size}`]) {
            ++size;
          }
          op[`${recordElement}_${size}`] = {
            key: recordElement,
            size: size,
          };
        }
        LT.op = op;
      };
      for (let event of events) {
        const { type, player, record } = event;
        switch (type) {
          case "PLAYER_JOIN":
            if (player === LT.player) {
              LOG(`${player} 加入了酒馆 <- 这个是你`);
              updateStatusInfo(`${player} (您) 加入了酒馆`);
            } else {
              LOG(`${player} 加入了酒馆`);
              updateStatusInfo(`${player} 加入了酒馆`);
            }
            updateMyCardsUI();
            break;
          case "PLAYER_LEAVE":
            LOG_ERR(`${player} 退出了酒馆`);
            updateStatusInfo(`${player} 退出了酒馆`, true);
            break;
          case "GAME_START":
            LOG_ERR(
              `游戏开始 注意👉(?是对方位置的牌 K,Q,J,A分别有6个, S是万能牌仅有2个)`
            );
            updateStatusInfo("游戏开始！请出牌", false);
            updateMyCardsUI();
            break;
          case "GAME_END":
            if (PRIVATE.watchInterval || PRIVATE.watchInterval > 0) {
              clearInterval(PRIVATE.watchInterval);
            }
            LOG_ERR(`游戏结束, 胜利者是: ${record}`);
            updateStatusInfo(`游戏结束！胜利者是: ${record}`, false);
            break;
          case "PLAYER_PLAY_CARDS":
            if (player === LT.player) {
              LOG(`您打出了 [ ${record} ]`);
              updateStatusInfo(`您打出了 [${record}]`);
              const myself = playerDataList.findLast(
                (it) => it.name === LT.player
              );
              myself && refreshItems(myself.items);
            } else {
              LOG(`${player} 打出了 [ ${record} ]`);
              updateStatusInfo(`${player} 打出了 [${record}]`);
            }
            updateMyCardsUI();
            break;
          case "PLAYER_SHOOT":
            LOG(`${player} 对自己的大脑门开了一枪 (${record}/6)`);
            updateStatusInfo(`${player} 对自己开枪 (${record}/6)`);
            break;
          case "PLAYER_DEATH":
            LOG_ERR(`倒霉催${player}盖了帽了`);
            updateStatusInfo(`${player} 被淘汰了`, true);
            break;
          case "PLAYER_BANG":
            if (player === LT.player) {
              LOG(`你对${PRIVATE.preWaitPlayer}发出质疑觉得出的牌有假`);
              updateStatusInfo(`您质疑了 ${PRIVATE.preWaitPlayer}`);
            } else {
              LOG(`${player}觉得${PRIVATE.preWaitPlayer}有诈`);
              updateStatusInfo(`${player} 质疑了 ${PRIVATE.preWaitPlayer}`);
            }
            LOG(`揭秘${record.player}出的牌是[ ${record.useItems} ]`);
            updateStatusInfo(
              `揭秘: ${record.player} 出的牌是 [${record.useItems}]`
            );
            break;
          case "WAIT_PLAYER_OPERATE":
            PRIVATE.preWaitPlayer = PRIVATE.waitPlayer;
            PRIVATE.waitPlayer = player;
            if (player === LT.player) {
              if (record === 1) {
                LOG(
                  `这轮您第一个出牌${LT.globalName}.cards(${LT.globalName}.op.浏览器提示)出牌, 例子${LT.globalName}.cards(${LT.globalName}.op.K_2, ${LT.globalName}.op.J_1)是将自己的2个K和一个J打出`
                );
                updateStatusInfo("轮到您第一个出牌");
              } else {
                LOG(
                  `轮到您操作了可通过${LT.globalName}.bang()拍桌子质疑上一家或者打出牌${LT.globalName}.cards(${LT.globalName}.op.浏览器提示)例子${LT.globalName}.cards(${LT.globalName}.op.K_2, ${LT.globalName}.op.J_1)`
                );
                updateStatusInfo("轮到您操作: 出牌或质疑上一家");
              }
            } else {
              LOG(`轮到了${player}操作`);
              updateStatusInfo(`等待 ${player} 操作...`);
            }
            break;
          case "REFRESH_ITEM":
            const { key, playItems } = record;
            refreshItems(playItems);
            LOG(
              `小B宅子在线发牌, 本轮关键牌是[ ${key} ]. 下面是玩家牌情况 可通过${LT.globalName}.show()主动查看当前牌局玩家牌`
            );
            updateStatusInfo(`本轮关键牌: [${key}]`);
            LT.show();
            updateMyCardsUI();
            break;
        }
      }
      version = lastVersion;
    }, 2000);
  };

  LT.cards = function (...useCards) {
    const uks = useCards.flatMap((card) => Array(card.size).fill(card.key));
    APIS.cards(PRIVATE.uuid, uks).then(PRIVATE.NONE);
  };

  LT.bang = function () {
    APIS.bang(PRIVATE.uuid).then(PRIVATE.NONE);
  };

  LT.show = function () {
    if (!PRIVATE.playerDataList) return;
    const ot = PRIVATE.playerDataList
      .filter((it) => it.status === "ALIVE")
      .map((it) => `${it.name} => [ ${it.items.join(", ")} ]`)
      .join(", ");
    LOG(ot);

    // 更新UI中的玩家牌信息
    updateMyCardsUI();
  };

  // 初始化UI
  createUI();

  LOG(
    `${LT.player}. 骗子酒馆控制台版本初始化完成, 项目地址: https://gitcode.com/mitu2/fish-game 欢迎提出问题`
  );
  LOG(`控制台输入${LT.globalName}.play()即可探索`);
  updateStatusInfo("准备好开始游戏，请输入 LT.play()");

  if (LT.uuid) {
    LT.play(LT.uuid).then();
  }
  window[LT.globalName] = LT;
}
